package com.kirk.cts.crawler.handler;

import org.apache.commons.lang.StringUtils;

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.Properties;

/**
 * <p> HttpProxySetUtil.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-29 22:33
 * @Description HTTP代理设置工具类
 */
public class HttpProxySetUtil {
    /**
     * 设置HTTP代理
     *
     * @param proxyHost 代理地址
     * @param proxyPort 代理端口
     * @param domain    域
     * @param userName  用户名
     * @param password  密码
     */
    public static void setHttpProxy(final String proxyHost, final String proxyPort,
                                    final String domain, final String userName, final String password) {
        if (StringUtils.isBlank(proxyHost) || StringUtils.isBlank(proxyPort)) {
            return;
        }
        Properties props = System.getProperties();
        props.setProperty("proxySet", "true");
        props.setProperty("http.proxyHost", proxyHost);
        props.setProperty("http.proxyPort", proxyPort);
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
            return;
        }
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                String userNameWithDomain = userName;
                if (StringUtils.isNotBlank(domain)) {
                    userNameWithDomain = domain + "\\" + userNameWithDomain;
                }
                return new PasswordAuthentication(userNameWithDomain, password.toCharArray());
            }
        });
    }

}
